import { pageTitles } from '~/configs/page'
import type { BreadcrumbItem } from '@nuxt/ui'

export const useBreadcrumb = () => {
  const route = useRoute()

  // 匹配路由模式（支持动态参数）
  const matchRoutePattern = (path: string) => {
    const patterns = Object.keys(pageTitles)

    for (const pattern of patterns) {
      if (pattern.includes('[')) {
        const regexPattern =
          '^' + pattern.replace(/\[[^\]]+\]/g, '[^/]+').replace(/\//g, '\\/') + '$'
        const regex = new RegExp(regexPattern)
        if (regex.test(path)) {
          return pattern
        }
      } else if (pattern === path) {
        return pattern
      }
    }
    return ''
  }

  // 获取页面标题
  const getPageTitle = (path: string) => {
    const pattern = matchRoutePattern(path)
    return pattern ? pageTitles[pattern] : '未知页面'
  }

  // 自动推导父级路径
  const getParentPath = (path: string): string => {
    if (path === '/') return ''
    const segments = path.split('/').filter(Boolean)
    segments.pop()
    return segments.length ? `/${segments.join('/')}` : '/'
  }

  // 生成面包屑
  const generateBreadcrumb = (): BreadcrumbItem[] => {
    const breadcrumb: BreadcrumbItem[] = []
    let currentPath = route.path

    // 从当前路径开始，逐级向上推导
    while (currentPath) {
      const title = getPageTitle(currentPath)

      breadcrumb.unshift({
        label: title || '',
        to: currentPath
      })

      // 推导父级路径，如果是根路径则停止
      const parentPath = getParentPath(currentPath)
      if (!parentPath) break
      currentPath = parentPath
    }

    return breadcrumb
  }

  return {
    generateBreadcrumb,
    getPageTitle
  }
}
